<template>
  <!-- 修改组件标签名 -->
  <AppMaster :name="name">
    <!-- 页面表格展示数据 - 重构为设备列表 -->
    <div class="bodyc0">
      <div class="bodyc1">
        <!-- 可保留新增设备按钮（如需） -->
        <el-button type="primary" @click="orderDevice">订阅主题</el-button>
        <!-- <el-button type="primary" @click="dialogVisible = true">新增设备</el-button> -->
      </div>
      <div class="center">
        <!-- 表格数据从tableData改为devices -->
        <el-table :data="devices" style="width: 100%">
          <el-table-column prop="id" label="设备ID" width="180"></el-table-column>
          <el-table-column prop="name" label="设备名称" width="180"></el-table-column>
          <!-- <el-table-column prop="status" label="状态" width="180">
            <template v-slot="scope">
              <span>{{ scope.row.status === 1 ? "在线" : "离线" }}</span>
            </template>
          </el-table-column> -->
          <!-- 操作列改为开启/关闭按钮 -->
          <el-table-column label="操作" width="240">
            <template v-slot="scope">
              <el-button type="primary" @click="startDevice(scope.row)">开启</el-button>
              <el-button type="danger" @click="stopDevice(scope.row)">关闭</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 移除原主题管理和设备选择对话框 -->
  </AppMaster>
</template>

<script>
import AppMaster from "@/components/AppMaster.vue";
export default {
  name: "TopicManager",
  components: {
    AppMaster,
  },
  data() {
    return {
      // 保留设备列表数据作为主要数据源
      devices: [
        { id: "ChongQing_JiuLongPo_ErLang_panlongRoad_0000", name: "盘龙路0000", status: 1 },
      ],
      name: "",
      // 移除原主题管理相关数据(form/dialogVisible/tableData等)
    };
  },
  methods: {
    // 订阅
    async orderDevice() {
      // try {
        const response = await this.$axios.post(
          this.$apiBaseUrl+"/api/mqtt/subscribe",
          // this.$apiBaseUrl+"/api/mqtt/subscribe",
          { topics: ["testtopic/recv", "testtopic/send"] },
          {
            headers: {
              "Content-Type": "application/json",
              token: JSON.parse(sessionStorage.getItem("user")).passWord,
            },
          }
        );

        if (!response.errorMsg) {
          this.$message({ type: "success", message: "订阅成功" });
          // device.status = 1; // 更新设备状态为在线
        }else{
          this.$message({ type: "error", message: response.errorMsg });
        }
      // } 
      // catch (error) {
      //   console.error("设备开启失败:", error);
      //   this.$message({ type: "error", message: "设备开启失败" });
      // }
    },
    // 新增设备开启方法
    async startDevice(device) {
      console.log("开启设备:", device);

      try {
        // const generateUUID = () => {
        //   return crypto.randomUUID().replace(/-/g, "");
        // };
        const generateUUID = () => {
          // 自定义UUID生成函数，兼容所有浏览器环境
          return 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            const r = Math.random() * 16 | 0;
            const v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
          });
        };
        const response = await this.$axios.post(
          this.$apiBaseUrl+"/api/mqtt/publish",
          // this.$apiBaseUrl+"/api/mqtt/publish",
          {
            topic: "testtopic/send",
            message: JSON.stringify({
              deviceID: device.id,
              messageID: generateUUID(),
              device01: "ONX",
              device02: "ONX",
            }),
          },

          {
            headers: {
              "Content-Type": "application/json",
              token: JSON.parse(sessionStorage.getItem("user")).passWord,
            },
          }
        );

        if (!response.data.errorMsg) {
          this.$message({ type: "success", message: "设备开启成功" });
        }
      } catch (error) {
        console.error("设备开启失败:", error);
        this.$message({ type: "error", message: "设备开启失败" });
      }
    },
    // 新增设备关闭方法
    async stopDevice(device) {
      console.log("开启设备:", device);

      try {
        // const generateUUID = () => {
        //   return crypto.randomUUID().replace(/-/g, "");
        // };
        const generateUUID = () => {
          // 自定义UUID生成函数，兼容所有浏览器环境
          return 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            const r = Math.random() * 16 | 0;
            const v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
          });
        };
        const response = await this.$axios.post(
          this.$apiBaseUrl+"/api/mqtt/publish",
          // this.$apiBaseUrl+"/api/mqtt/publish",
          {
            topic: "testtopic/send",
            message: JSON.stringify({
              deviceID: device.id,
              messageID: generateUUID(),
              device01: "OFF",
              device02: "OFF",
            }),
          },

          {
            headers: {
              "Content-Type": "application/json",
              token: JSON.parse(sessionStorage.getItem("user")).passWord,
            },
          }
        );

        if (!response.data.errorMsg) {
          this.$message({ type: "success", message: "设备关闭成功" });
        }
      } catch (error) {
        console.error("设备开启失败:", error);
        this.$message({ type: "error", message: "设备关闭失败" });
      }
    },
  },
  mounted() {
    this.name = JSON.parse(sessionStorage.getItem("user")).name;
    // 可添加设备列表初始化加载逻辑
    // this.loadDevices();
  },
};
</script>

<style scoped>
.bodyc0 {
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #fff;
  flex: 1;
}
.AiChatView {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: row;
  background-color: #f1f1f1;
}
.left {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 100%;
  width: 200px;
  background-color: rgb(241, 241, 241);
}
.leftHeader {
  height: 80px;
  width: 100%;
  background-color: rgb(241, 241, 241);
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  border-bottom: 1px rgb(221, 221, 221) solid;
  margin-bottom: 10px;
}
.leftBody {
  width: 100%;
  flex: 1;
  background-color: rgb(241, 241, 241);
  display: flex;
  flex-direction: column;
  align-items: center;
}
.leftBodyList {
  display: flex;
  height: 50px;
  width: 80%;
  border-radius: 10px;
}
.leftHeaderL {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.leftHeaderLimg {
  width: 30px;
  height: 30px;
}
.leftHeaderLimg1 {
  width: 20px;
  height: 20px;
}
.leftHeaderR {
  margin-right: 26px;
  margin-left: 5px;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.right {
  overflow: hidden;
  height: 100%;
  flex: 1;
  background-color: #ebbdbd;
  display: flex;
  flex-direction: column;
}
.rightHeader {
  height: 80px;
  background-color: #fff;
  width: 100%;
  display: flex;
  /* border-left: 1px rgb(241, 241, 241) solid; */
}
.rightHeader1 {
  width: 1px;
  height: 80px;
  background-color: rgb(241, 241, 241);
}
.rightHeader2 {
  display: flex;
  align-items: center;
  flex: 1;
}
.rightHeader21 {
  flex: 1;
}
.rightHeader22 {
  width: 40px;
  height: 40px;
  border-radius: 20px;
  background-color: rosybrown;
  margin-right: 20px;
}
.rightHeader23 {
  height: 100%;
  margin-right: 20px;
}
.rightHeader24 {
  height: 100%;
  margin-right: 20px;
}
.rightHeader241 {
  width: 20px;
  margin-right: 20px;
}
.leftBodyList2 {
  font-size: 12px;
  margin-left: 10px;
  margin-right: 26px;
}
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
.rightBody {
  width: 100%;
  /* flex: 1; */
  height: calc(100vh - 80px);
  background-color: #fff;
  display: flex;
  justify-content: center;
}
.rightBody1 {
  width: 550px;
  background-color: #fff;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.rightBody1a {
  width: 550px;
  background-color: #fff;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.rightBody11 {
  width: 100%;
  font-size: 24px;
  font-weight: 700;
}
.rightBody12 {
  margin-top: 15px;
  width: 100%;
  height: 100px;
  background-color: #fff;
  border-radius: 15px;
  border: solid 1px #cfcfcf;
  display: flex;
  flex-direction: column;
}
.rightBody121 {
  flex: 1;
  width: 100%;
  /* background-color: aqua; */
}
.rightBody122 {
  height: 50px;
  width: 100%;
  /* background-color: rgb(196, 196, 196); */
  display: flex;
}
.rightBody1222 {
  margin-right: 8px;
  width: 27px;
  height: 100%;
}
.rightBody1221 {
  width: 27px;
  /* height: 100%; */
  align-items: center;
}
.rightBody1220 {
  flex: 1;
}
.textarea2 {
  padding: 0 10px 10px 10px;
  width: 96%;
  border: none;
  outline: none;
}
.rightBody123 {
  height: 140px;
}
.rBody11 {
  flex: 1;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
}
.marginbottom {
  margin-bottom: 20px;
}
.usercss {
  margin-bottom: 20px;
  display: flex;
}
.botcss {
  margin-bottom: 20px;
  display: flex;
  flex-direction: row-reverse;
}
.a1a {
  flex: 1;
}
.a2a {
  background-color: #f7f7f7;
  padding: 10px;
  border-radius: 10px;
  font-size: 13px;
  font-weight: 400;
  max-width: 50%;
  display: flex;
  flex-direction: column;
}
.a3a {
  display: flex;
  flex-direction: column;
  font-size: 13px;
  font-weight: 400;
}
</style>
